package reader

import (
	"context"
	"gitee.com/alex_li/rodinbell/etc"
	"github.com/lishimeng/go-log"
	serial "github.com/tarm/goserial"
	"time"
)

func Open(ctx context.Context, options *Options) (session Reader) {

	log.Info("Open connection %s:%d", options.PortName, options.BaudRate)

	//serialOptions := serial.OpenOptions{
	//	PortName: options.PortName,
	//	BaudRate: options.BaudRate,
	//	DataBits: 8,
	//	StopBits: 1,
	//	MinimumReadSize: 4,
	//}
	//port, err := serial.Open(serialOptions)

	serialOptions := &serial.Config{
		Name: options.PortName,
		Baud: int(options.BaudRate),
	}
	port, err := serial.OpenPort(serialOptions)

	if err != nil {
		log.Info(err)
		panic(err)
	}
	session = Reader{Ctx: ctx, State: true}
	session.opts = *options
	session.readBuffer = make([]byte, 128)
	session.conn = port

	_ = setPower(session, etc.Config.Antenna.Power)

	go session.Watch()

	return session
}

func (session *Reader) Watch() {

	for {
		select {
		case <-session.Ctx.Done():
			session.Close()
			break
		default:
			time.Sleep(500*time.Millisecond)
		}
	}
}

func (session Reader) Close () {
	_ = session.conn.Close()
}

func (session Reader) Inventory(callback Callback) () {

	for _, antenna := range session.opts.Antennas {
		inventoryAntenna(session, antenna, callback)
		time.Sleep(time.Millisecond*30) // 天线间隔
	}
}

func (session Reader) FastInventory(callback Callback) () {

	fastInventory(session)
	handleInventoryResp(session, callback)
}

func inventoryAntenna(session Reader, antenna uint, callback Callback) {

	log.Debug("inventory antenna:%d", antenna)
	_ = selectAntenna(session, antenna)
	inventoryStart(session)
	handleInventoryResp(session, callback)
}

func handleInventoryResp(session Reader, callback Callback) {
	for {
		inventoryInfo := handleInventory(session)
		if inventoryInfo.PacketType == TagSummaryType {
			log.Debug("inventory complete")
			break
		}
		if inventoryInfo.PacketType == InventoryError {
			log.Debug("inventory exit with err")
			break
		}
		tag := inventoryInfo.TagInfo
		callback(tag)
	}
}

